package cn.digger.md2pdf.service;

import cn.digger.md2pdf.util.Html2Pdf;
import cn.digger.md2pdf.util.Md2HtmlUtil;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Service
public class Md2PdfService {

    @PostMapping("/convert")
    public ResponseEntity<ByteArrayResource> convertMdToPdf(@RequestParam("file") MultipartFile file) throws IOException {
        // 1. Check if the file is a Markdown file
        if (!"text/markdown".equals(file.getContentType()) && !Objects.requireNonNull(file.getOriginalFilename())
                .toLowerCase().endsWith(".md")) {
            // If not a markdown file, return an empty PDF
            ByteArrayOutputStream emptyPdf = new ByteArrayOutputStream();
            Html2Pdf.convertHtml2Pdf("", emptyPdf); // Convert empty HTML to PDF
            ByteArrayResource resource = new ByteArrayResource(emptyPdf.toByteArray());

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=empty.pdf")
                    .contentType(MediaType.APPLICATION_PDF)
                    .contentLength(resource.contentLength())
                    .body(resource);
        }

        // 2. Read Markdown content
        String markdownContent = new String(file.getBytes(), StandardCharsets.UTF_8);

        // 3. Convert Markdown to HTML
        String htmlContent = Md2HtmlUtil.convertMd2Html(markdownContent);

        // 4. Convert HTML to PDF
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        Html2Pdf.convertHtml2Pdf(htmlContent, pdfOutputStream);

        ByteArrayResource resource = new ByteArrayResource(pdfOutputStream.toByteArray());

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" +
                        Objects.requireNonNull(file.getOriginalFilename()).replace(".md", ".pdf") + "\"")
                .contentType(MediaType.APPLICATION_PDF)
                .contentLength(resource.contentLength())
                .body(resource);
    }
}